package com.evan.petiymanta.glide;

import androidx.annotation.NonNull;

import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import com.bumptech.glide.load.model.MultiModelLoaderFactory;
import com.bumptech.glide.signature.ObjectKey;
import com.evan.petiymanta.service.FileServiceHolder;
import com.evan.petiymanta.service.IFileExplorerService;

import java.nio.ByteBuffer;

public class ShizukuModelLoader implements ModelLoader<String, ByteBuffer> {

    @Override
    public LoadData<ByteBuffer> buildLoadData(@NonNull String path, int width, int height, @NonNull Options options) {
        return new LoadData<>(new ObjectKey(path), new DataFetcher<ByteBuffer>() {
            @Override
            public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super ByteBuffer> callback) {
                try {
                    IFileExplorerService service = FileServiceHolder.getFileService();
                    if (service == null) {
                        callback.onLoadFailed(new NullPointerException("FileService not connected"));
                        return;
                    }
                    byte[] bytes = service.readImageFile(path);
                    ByteBuffer buffer = ByteBuffer.wrap(bytes);
                    callback.onDataReady(buffer);
                } catch (Exception e) {
                    callback.onLoadFailed(e);
                }
            }

            @Override
            public void cleanup() {
            }

            @Override
            public void cancel() {
            }

            @Override
            public @NonNull Class<ByteBuffer> getDataClass() {
                return ByteBuffer.class;
            }

            @Override
            public @NonNull DataSource getDataSource() {
                return DataSource.LOCAL;
            }
        });
    }

    @Override
    public boolean handles(@NonNull String path) {
        return path.contains("/storage/emulated/0/Android/data/");
    }

    public static class Factory implements ModelLoaderFactory<String, ByteBuffer> {
        @NonNull
        @Override
        public ModelLoader<String, ByteBuffer> build(@NonNull MultiModelLoaderFactory multiFactory) {
            return new ShizukuModelLoader();
        }

        @Override
        public void teardown() {
        }
    }
} 